<template>
	<el-dialog :title="title" :modal-append-to-body="false" :visible.sync="isShow" :close-on-click-modal="false" :before-close="close" width="1100px">
		<div class="form-box">
			<el-form ref="form" :model="form" :rules="rules" label-width="110px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="页面头图海报" prop="posterUrl">
							<el-upload
								ref="upload"
								:class="{'upload-cover-disabled': form.posterUrl}"
								list-type="picture-card"
								:file-list="fileList"
								:limit="1"
								:accept="'image/*'"
								action=""
								:http-request="getQiniuToken"
								:on-remove="handleRemove"
							>
								<i class="el-icon-plus avatar-uploader-icon" slot="default" ></i>
							</el-upload>
							
							<el-alert class="upload-progress" type="warning" title="" v-if="isUploading">
								<template slot="title">
									<div class="upload-progress-text">
										<i class="el-icon-loading"></i>
										<span>上传中，请勿关闭窗口!</span>
									</div>
								</template>
							</el-alert>
							<el-alert class="upload-progress" type="success" title="上传成功!" show-icon v-if="isUploadingSuccess"></el-alert>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="24">
						<el-form-item label="专题页标题" prop="title">
							<el-input v-model="form.title" placeholder="请填写专题页的标题" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="16">
						<el-form-item label="专题活动时间" prop="startTime">
							<el-date-picker
								v-model="time"
								type="datetimerange"
								range-separator="至"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
								@change="chooseTime"
								style="width: 100%;"
							></el-date-picker>
						</el-form-item>
					</el-col>
					
					<el-col :span="8">
						<el-form-item label="排序" prop="sort" label-width="80px">
							<el-input v-model="form.sort" placeholder="请填写排序序号" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row v-if="isEdit">
					<el-col :span="24">
						<el-form-item label="上架状态" prop="publishStatus">
							<el-radio-group v-model="form.publishStatus">
								<el-radio :label="1">上架</el-radio>
								<el-radio :label="0">下架</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				
				<el-row>
					<el-col :span="24">
						<el-form-item label="详细描述" prop="productDesc">
							<d2-ueditor v-model="content"></d2-ueditor>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</div>
		
		<div slot="footer">
			<el-button type="primary" @click="submit">保 存</el-button>
			<el-button @click="reset" v-if="!isEdit">重 置</el-button>
			<el-button @click="close">取 消</el-button>
		</div>
	</el-dialog>
</template>

<script>
	import dayjs from 'dayjs'
	import * as qiniu from 'qiniu-js'
	import { getQiniuToken } from '@api/common/common'
	import { addSpecialPage, editSpecialPage, editSpecialPageContent, getSpecialPageContent } from '@api/platform/platformMarketing'
	export default {
		props: {
			isShow: Boolean,
			item: Object,
			isEdit: Boolean,
		},
		data() {
			let validatePost = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请上传专题页头图海报'));
				} else {
					callback();
				}
			}
			return {
				form: {
					title: '',
					sort: '',
					posterUrl: '',
					startTime: '',
					endTime: '',
					publishStatus: 0,
				},
				rules: {
					posterUrl: [{required: true, validator: validatePost, trigger: 'blur'}],
					title: [{ required: true, message: '请填写专题页标题', trigger: 'blur' }],
					startTime: [{ required: true, message: '请选择开始和结束时间', trigger: 'blur' }],
				},
				content: '',
				time: [],
				
				fileList: [],
				isUploading: false,
				isUploadingSuccess: false,
				
				qiniuKey: '',
				qiniuToken: '',
				qiniuPutExtra: {},
				qiniuConfig: {
					useCdnDomain: true,
					retryCount: 6,
				},
			}
		},
		computed: {
			title() {
				let title = '专题页';
				if(this.isEdit) {
					title = '编辑' + title;
				} else {
					title = '添加' + title;
				}
				return title;
			}
		},
		watch: {
			isShow(val) {
				if(val) {
					if(this.isEdit) {
						this.initForm();
					}
				}
			},
			'form.posterUrl': {
				handler(val) {
					if(val) {
						this.$refs['form'].clearValidate('posterUrl');
					}
				},
				deep: true
			},
		},
		methods: {
			initForm() {
				this.form.title = this.item.title;
				this.form.sort = this.item.sort;
				this.form.posterUrl = this.item.posterUrl;
				this.form.startTime = this.item.startTime;
				this.form.endTime = this.item.endTime;
				this.form.publishStatus = this.item.publishStatus;
				this.time = [this.item.startTime, this.item.endTime];
				
				this.fileList.push({
					name: 'posterUrl',
					url: this.form.posterUrl
				});
				
				this.getContent();
			},
			getContent() {
				getSpecialPageContent(this.item.id)
					.then(res => {
						this.content = res.data;
					})
			},
			
			chooseTime(val) { //选择时间
				this.form.startTime = val[0];
				this.form.endTime = val[1];
			},
			
			//七牛云上传图片
			getQiniuToken(file) {
				this.isUploading = true;
				this.isUploadingSuccess = false;
				
				// console.log(file.file.name)
				let name = file.file.name.split('.');
				let subffixName = '.' + name[name.length-1];
				
				getQiniuToken({subffixName: subffixName})
					.then(res => {
						this.qiniuToken = res.data.token;
						this.qiniuKey = res.data.key;
						this.uploadFile(file);
					})
			},
			uploadFile(file) {
				//qiniu.upload(file, key, token, putExtra, config)
				const observable = qiniu.upload(
					file.file,
					this.qiniuKey,
					this.qiniuToken,
					this.qiniuPutExtra,
					this.qiniuConfig
				)
				
				// 上传开始
				observable.subscribe({
					next: res => {
						console.log(res)
					},
					error: err => {
						console.log(err)
						this.handleError(err, file)
					},
					complete: res => {
						console.log(res)
						this.handleSuccess(res, file)
					},
				});
			},
			
			handleSuccess (response, file) {
				// console.log('response:', response)
				this.$message.success('上传成功');
				
				this.fileList.push(process.env.VUE_APP_OSS_DOMAIN + response.key);
				this.form.posterUrl = process.env.VUE_APP_OSS_DOMAIN + response.key;
				this.isUploadingSuccess = true;
				this.isUploading = false;
			},
			handleError (err, file) {
				console.log(err)
				this.$message.error('上传失败，请重新上传!');
				this.fileList.splice(0);
				this.isUploading = false;
			},
			handleRemove() {
				this.form.posterUrl = '';
				this.$refs.upload.clearFiles();
				this.isUploading = false;
				this.isUploadingSuccess = false;
			},
			
			submit() { //提交添加or编辑
				this.$refs.form.validate(valid => {
					if (valid) {
						let params = {
							title: this.form.title,
							sort: this.form.sort,
							posterUrl: this.form.posterUrl,
							startTime: this.form.startTime,
							endTime: this.form.endTime,
						}
						if(this.isEdit) {
							params.id = this.item.id;
							params.publishStatus = this.form.publishStatus;
							
							editSpecialPage(params)
								.then(() => {
									if(this.content) {
										this.submitContent(this.item.id);
									} else {
										this.$message.success('专题页修改成功！');
										this.close();
										this.$emit('submit');
									}
								})
						} else {
							addSpecialPage(params)
								.then(res => {
									if(this.content) {
										this.submitContent(res.data);
									} else {
										this.$message.success('专题页添加成功！');
										this.close();
										this.$emit('submit');
									}
								})
						}
					}
				})
			},
			submitContent(id) {
				editSpecialPageContent({
					topicId: id,
					content: this.content
				})
					.then(() => {
						this.$message.success(`专题页${this.isEdit ? '编辑' : '添加'}成功！`);
						this.close();
						this.$emit('submit');
					})
			},
			
			reset() {
				this.form.title = '';
				this.form.sort = '';
				this.form.posterUrl = '';
				this.form.startTime = '';
				this.form.endTime = '';
				this.form.publishStatus = 0;
				
				this.$refs.upload.clearFiles();
				this.fileList = [];
				this.isUploading = false;
				this.isUploadingSuccess = false;
			},
			
			close() {
				this.$emit('close');
				this.reset();
			},
		}
	}
</script>

<style lang="scss" scoped>
	.form-box {
		padding: 20px 30px;
	}
	.el-alert {
		line-height: normal;
	}
	
	.upload {
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, .5);
		position: relative;
	}
	.upload-cover-disabled {
		::v-deep .el-upload {
			display: none;
		}
	}
</style>